<template>
  <view class="setting-page" >
    <view class="setting-card" > 
      <button class="avatar-wrapper" plain open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image class="avatar" :src="avatarUrlRef ? avatarUrlRef : userDefault"></image>
      </button> 
      <nut-cell-group >
        <nut-cell title="昵称">
          <template #desc>
            <input type="nickname" class="nickname-input" placeholder="请输入昵称" :value="nickName"   @change="inputNickName" />
          </template>
        </nut-cell>
        <nut-cell title="日主" desc="选择日主"  @click="rizhuVisible = true"> 
          <template #desc>
            <view style="color: #797777;" >{{rizhu}}</view>
          </template>
        </nut-cell>
        <nut-cell title="生日" desc="选择生日" @click="showBottom = true" >
          <template #desc>
            <view style="color: #797777;" >{{birthDay}}</view>
          </template>
        </nut-cell>
      </nut-cell-group>
    </view>
   
    <view class="submit-btn"  @click="confirmInfo">
      设置信息
    </view>

    <!-- 生日 -->
    <nut-popup position="bottom" round :custom-style="{  height: '50%', zIndex: 100000}" v-model:visible="showBottom">
      <view class="calendar-type">
        <view 
          v-for="item in calendarType" 
          :key="item.key"
          :class="['type-item', calendarActive === item.key ? 'active' : '']"
          @click="selectType(item.key)"
        >
          {{item.title}}
        </view>
      </view>
      <nut-date-picker
       :min-date="minDate"
        :max-date="maxDate"
        type="datetime"
        :formatter="formatter"
        v-model="currentDate"
        three-dimensional
        is-show-chinese
        @confirm="onConfirmBirthday">
      </nut-date-picker>
    </nut-popup>
    <!-- 日主 -->
      <nut-action-sheet
        v-model:visible="rizhuVisible"
        :menu-items="propertys"
        @choose="chooseRizhu"
      >
      </nut-action-sheet>
  </view>
</template>
<script lang='ts' setup >
import userDefault from '@/static/common/ava-my.png';
import { useUserStore } from '@/store';
import dayjs from 'dayjs';
import { DatePickerColumnType, PickerOption } from 'nutui-uniapp';
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'

  const { calendar } = require('../../utils/calendar.js')

  const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

  const avatarUrlRef = ref('')

  const nickName = ref('')

  const calendarType = [{title: '公历', key: 0}, {title: '农历', key: 1}]

  const calendarActive = ref(0)

  const minDate = new Date(1970, 0, 1)

  const maxDate = new Date()

  const userStore = useUserStore()

  const { userinfo } = storeToRefs(userStore)

  const currentDate = ref()

  const showBottom = ref(false)

  const rizhuVisible = ref(false)

  const rizhu = ref('请选择日主')

  const birthDay = ref('请选择生日')

  const birthDayOrigin = ref<any>('')

  const propertys = ref([
    {name: '身强', img: '/static/my/shenqiang.png', value: 'shenqiang'},
    {name: '从强', img: '/static/my/congqiang.png', value: 'congqiang'},
    {name: '中和', img: '/static/my/zhonghe.png', value: 'zhonghe'},
    {name: '身弱', img: '/static/my/shenruo.png', value: 'shenruo'},
    {name: '从弱', img: '/static/my/congruo.png', value: 'congruo'}
  ])

  const chooseRizhu = (record: any) => {
    rizhu.value = record.name
  }


  const formatter = (type: DatePickerColumnType, option: PickerOption) => {
    if (calendarActive.value === 0) {
      return option
    }
    if (type === 'month') {
      const month = calendar.toChinaMonth(option.text)
      option.text = month
    }
    if (type ==='day') {
      const day = calendar.toChinaDay(option.text)
      option.text = day
    }
    // if (type === 'year') {
    //   const year = calendar.toGanZhiYear(option.text)
    //   option.text = year + `(${option.text})`
    // }
    
    return option
  }

  const onConfirmBirthday = (record: any) => {
    birthDayOrigin.value = record.selectedOptions
    if (calendarActive.value === 0) {
      birthDay.value = dayjs(record.date).format('YYYY-MM-DD HH:mm')
    } else {
      const [year, month, day, hours, min] = record.selectedOptions
      birthDay.value = `${year.text}年${month.text}${day.text} ${hours.text}:${min.text}`
      console.log('calendar.lunar2solar(year.text, month.text, day.text):', calendar.lunar2solar(year.value, Number(month.value), Number(day.value)));
    }
 
    showBottom.value = false
  }

  const onChooseAvatar = (e: any) => {  
    const { avatarUrl } = e.detail
    const fileSystemManager = uni.getFileSystemManager()
    fileSystemManager.readFile({
      filePath: avatarUrl,
      encoding: 'base64',
      success (res) {
        console.log('res:', res);
        const base64Data = res.data
        const base64Header = 'data:image/png;base64,'
        const base64Image = base64Header + base64Data
        avatarUrlRef.value = base64Image
      }
    })
  }

  const inputNickName = (e) => {
    nickName.value = e.detail.value
  }

  const confirmInfo = async () => {
    if (!avatarUrlRef.value) return uni.showToast({title: '请设置头像', icon: 'none'})
    if (!nickName.value) return uni.showToast({title: '请填写昵称', icon: 'none'})
    if (!rizhu.value) return uni.showToast({title: '请选择日主', icon: 'none'})
    if (!birthDay.value) return uni.showToast({title: '请选择生日', icon: 'none'})
    console.log('birthDay.value:', birthDay.value);
  //  birthDayOrigin.value
    let _birthday = ''
    if ( calendarActive.value === 1) {
      const [year, month, day, hours, min] = birthDayOrigin.value

      const { cYear, cMonth, cDay } = calendar.lunar2solar(year.value, Number(month.value), Number(day.value))
      
      _birthday = `${cYear}-${cMonth}-${cDay} ${hours.text}:${min.text}`

    }

    const { status } = await userStore.uploadUserInfo({
      avatar: avatarUrlRef.value,
      name: nickName.value,
      riZhu: rizhu.value,
      birthday: calendarActive.value === 1 ? _birthday :  birthDay.value
    })
    if (status == 200) {
      uni.navigateBack()
    }
  }

  const selectType = (key) => {
    calendarActive.value = key
  }

  onLoad(() => {
    console.log('userinfo.value.:', userinfo.value);
    
    if (userinfo.value.id) {
      avatarUrlRef.value = userinfo.value.avatar || defaultAvatarUrl
      nickName.value = userinfo.value.name || ''
      rizhu.value = userinfo.value.riZhu || '请选择日主'
      birthDay.value = userinfo.value.birthday || '请选择生日'
      console.log('birthDay.value:', birthDay.value);
      
    }
  })
  </script>
<style lang='scss' scoped >
@import '../../styles/index.scss';
.setting-page {
  width: 100vw;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 32rpx;
  box-sizing: border-box;

  .setting-card {
    background: #fff;
    border-radius: 24rpx;
    padding: 48rpx 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

    .avatar-wrapper {
      width: 180rpx;
      height: 180rpx;
      padding: 0;
      background: none;
      border: none;
      margin: 0 auto 48rpx;
      display: block;
      background-color: transparent;
      .avatar {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        // border: 6rpx solid #fff;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      }
    }

    .nickname-input {
      color: #000;
    }

    :deep(.nut-cell-group) {
      margin-top: 32rpx;

      .nut-cell {
        padding: 28rpx 24rpx;
        margin-bottom: 12rpx;

        .nut-cell__title {
          font-size: 28rpx;
          color: #333;
        }

        .nut-cell__desc {
          flex: 1;
          text-align: right;
          
          input {
            width: 100%;
            height: 56rpx;
            padding: 0 16rpx;
            font-size: 28rpx;
            color: #333;
            text-align: right;

            &::placeholder {
              color: #999;
            }
          }
        }
      }
    }
  }

  .confirm-btn {
    width: 700rpx;
    height: 86rpx;
    background: $main-color;
    border-radius: 48rpx;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 82rpx;
  }
}

.calendar-type {
  display: flex;
  justify-content: space-between;
  padding: 12rpx;
  background: #f5f5f5;
  border-radius: 16rpx;
  position: relative;
  margin: 24rpx;

  .type-item {
    flex: 1;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
    z-index: 1;
    transition: color 0.3s ease;

    &.active {
      color: #fff;
    }

    // 选中背景
    &.active::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: $main-color;
      border-radius: 12rpx;
      z-index: -1;
      transition: all 0.3s ease;
    }
  }
}

// 添加底部按钮样式（如果需要）
.submit-btn {
  width: 90%;
  height: 88rpx;
  background: $main-color;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin: 48rpx auto;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 16rpx rgba($main-color, 0.3);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba($main-color, 0.2);
  }
}
</style>